<?php

namespace App\Module\Api\Controllers;

use App\System\Base\Services\NotifyService;
use App\System\Cis\Services\RepeatedEliminationService;
use Illuminate\Support\Facades\Log;
use Omnipay\Omnipay;

/**
 *回调业务
 */
class NotifyController extends Controller
{

    /**
     * 支付宝回调业务
     * @return array
     */
    public function aliPay()
    {
      /* $res = new RepeatedEliminationService();
        $res->findAllTheUsersToSend();
        die;*/
        $path = storage_path('app/public/logs/aliPay.log');
        Log::useDailyFiles($path);
        Log::info('支付宝异步通知信息：'.var_export(request()->all(),true));
        $gateway = Omnipay::create('Alipay_AopApp');
        $gateway->setAlipayPublicKey(config("pay.ali_public_key"));
        $request = $gateway->completePurchase();
        $request->setParams($_POST);

        try {
            $response = $request->send();

            if($response->isPaid()){
                /**
                 * Payment is successful
                 */
                NotifyService::orderNotify($_POST['out_trade_no'],2,$_POST['trade_no']);//执行回调业务
                Log::info('支付状态：成功');
                die('success'); //The response should be 'success' only
            }else{
                /**
                 * Payment is not successful
                 */
                Log::info('支付状态：失败');
                die('fail');
            }
        } catch (Exception $e) {
            /**
             * Payment is not successful
             */
            die('fail');
        }
    }

    /**
     * 微信回调业务
     */
    public function wxPay()
    {
       /* if(isset($_GET['out_trade_no']))
        {
            NotifyService::orderNotify($_GET['out_trade_no'],1,$_GET['transaction_id']);//执行回调业务
            die;
        }*/
        $path = storage_path('app/public/logs/wxPay.log');
        Log::useDailyFiles($path);
        Log::info('微信异步通知信息：'.file_get_contents('php://input'));
        $gateway    = Omnipay::create('WechatPay');
        $gateway->setAppId(config('pay.wx_app_id'));
        $gateway->setMchId(config('pay.wx_mch_id'));
        $gateway->setApiKey(config('pay.wx_api_key'));
        $response = $gateway->completePurchase([
            'request_params' => file_get_contents('php://input')
        ])->send();

        if ($response->isPaid()) {
            //pay success
            $data = $response->getRequestData();
            NotifyService::orderNotify($data['out_trade_no'],1,$data['transaction_id']);//执行回调业务
            Log::info('支付状态：成功'.$data['out_trade_no']);
            die;
        }else{
            Log::info('支付状态：失败');
            //pay fail
            die;
        }
    }

}
